<?php
	class Location_model extends MY_Model{
		
		public function __construct(){
			parent::__construct();
		}
		
		public function get_location($id=FALSE){
			$this->db->select('l.*, d.name, d.id AS d_id, ci.id AS ci_id, city, c.iso, c.name AS c_name');
			$this->db->from('location l');
			$this->db->join('district d', 'd.id = l.district_id', 'left');
			$this->db->join('city ci', 'ci.id = d.city_id', 'left');
			$this->db->join('country c', 'c.iso = ci.country_code', 'left');
			
			if($id === FALSE){
				$this->db->limit($this->record_per_page, $this->limit);
				$query = $this->db->get();				
				return $query->result_array();
			}
			else{
				$this->db->where('l.id='.$id, NULL, FALSE);
				$query = $this->db->get();
				return $query->row_array();
			}			
		}
		
		public function get_location_list(){
			$this->db->select('l.*, d.name, d.id AS d_id, ci.id AS ci_id, city, c.iso, c.name AS c_name');
			$this->db->from('location l');
			$this->db->join('district d', 'd.id = l.district_id', 'left');
			$this->db->join('city ci', 'ci.id = d.city_id', 'left');
			$this->db->join('country c', 'c.iso = ci.country_code', 'left');
			$query = $this->db->get();	
			return $query->result_array();
		}
		
		public function get_total(){
			return count($this->get_location_list());
		}
		
		public function save(){
			$id 	= $this->input->post('id');
			
			$data = array(
				"address" 		=> $this->input->post('address'),
				"description" 	=> $this->input->post('description'),
				"district_id" 	=> $this->input->post('district_id')				
			);
			if(empty($id))
				return $this->db->insert('location', $data);
			else{
				$this->db->where('id', $id);
				return $this->db->update('location', $data);
			}
		}
		
		public function delete($id){
			$sql = "SELECT `id` FROM `kiosk` WHERE `location_id` = $id";
			$query = $this->db->query($sql);
			if($query->num_rows()==0){
				$this->db->where('id', $id);
				$this->db->delete('location');
			}
		}		
		
	}
?>